<?php

@set_time_limit(0);

/**
 * 计划任务执行
 * Some rights reserved：abc3210.com
 * Contact email:admin@abc3210.com
 */
class IndexAction extends BaseAction {

    function _initialize() {
        parent::_initialize();
        import('@.ORG.Util.Html');
    }

    //重写error
    public function error($message, $jumpUrl = '', $ajax = false) {
        
    }

    //重写success
    public function success($message, $jumpUrl = '', $ajax = false) {
        
    }

    //重写display
    public function display($templateFile = '', $charset = '', $contentType = '') {
        
    }

    public function buildHtml($htmlfile = '', $htmlpath = '', $templateFile = '') {
        parent::buildHtml($htmlfile, $htmlpath, $templateFile);
    }

    public function assign($name, $value = '') {
        parent::assign($name, $value);
    }

    public function index() {
        $this->refresh();
        $this->Tasks();
    }

    /**
     * 刷新任务 
     */
    protected function refresh() {
        $todaytime = time();
        $b = 0;
        $db = M("Gentasks");

        $rdata = $db->where(" isopen=1 and lasttime+dotime*60<$todaytime ")->select();

        if (!is_array($rdata)) {
            return;
        }

        $this->html = new Html();
        $this->html->pointer($this);
        //指定内容模块生成，没有指定默认使用GROUP_NAME
        define("GROUP_MODULE", "Contents");
        foreach ($rdata as $k => $r) {
            $b = 1;
            if ($r['type'] == 1) {//刷新首页
                if (CONFIG_GENERATE != '1') {
                    continue;
                }
                $page = 1;
                $j = 1;
                //分页生成
                do {
                    $this->html->index($page);
                    $page++;
                    $j++;
                } while ($j <= $_GET["_PAGES_"]);
            } else if ($r['type'] == 2) {//刷新栏目
                $catid = explode(",", $r['catid']);
                if (is_array($catid)) {

                    foreach ($catid as $cid) {
                        $page = 1;
                        $j = 1;
                        //开始生成列表
                        do {
                            $this->html->category($cid, $page);
                            $page++;
                            $j++;
                        } while ($j <= $_GET["_PAGES_"]);
                    }
                }
            } else if ($r['type'] == 3) {//刷新自定义页面
                $catid = explode(",", $r['catid']);
                if (is_array($catid)) {
                    C("USER_AUTH_ON",false);
                    $tpAction = A("Template/Custompage");
                    $CDb = D("Customtemp");
                    $html = new Html();
                    $html->pointer($this);
                    foreach ($catid as $cid) {
                        $tempid = $cid;
                        $rs = $CDb->where(array("tempid" => $tempid))->find();
                        if ($rs) {
                            $cachepath = $tpAction->cachepath . $rs['tempid'] . ".php";
                            file_put_contents($cachepath, strip_whitespace($rs['temptext']));
                            $html->createhtml($cachepath, $rs);
                        }
                    }
                    C("USER_AUTH_ON",true);
                }
            }
            //更新任务执行时间
            $db->where(array('gid' => $r['gid']))->save(array(
                'lasttime' => $todaytime,
            ));
        }
        if ($b) {
            echo "最后执行时间：" . date("Y-m-d H:i:s", $todaytime) . "<br><br>";
        }
    }

    /**
     * 计划任务 
     */
    protected function Tasks() {
        $db = M("Task");
        $r = $db->where(array("isopen" => 1))->select();
        if (is_array($r)) {
            foreach ($r as $k => $v) {
                if ($lasttime = $this->CheckDoTask($v)) {
                    //执行任务
                    $file = LIB_PATH . 'ORG/Tasks/' . $v['filename'];
                    if (empty($v['filename']) || !file_exists($file)) {
                        continue;
                    }
                    if ($lasttime) {
                        echo"任务 [" . $v['name'] . "] 开始执行......<br/>";
                        @require_once($file);
                        $db->where(array("id" => $v['id']))->save(array(
                            "lastdo" => $lasttime
                        ));
                        echo"任务 [" . $v['name'] . "] 执行完毕，最后执行时间：" . date("Y-m-d H:i:s", $lasttime) . "<br/>";
                    }
                }
            }
        }
    }

    //检验是否执行
    protected function CheckDoTask($r) {
        $time = time();
        $date = date("j,w,G,i,Y,m");
        $dr = explode(',', $date);
        if ($r['doday'] != 0 && $r['doday'] != $dr[0]) {//日期
            return false;
        }
        if ($r['doweek'] != 0 && $r['doweek'] != $dr[1]) {//星期
            return false;
        }
        if ($r['dohour'] != 0 && $r['dohour'] != $dr[2]) {//小时
            return false;
        }
        $min = (int) $dr[3];
        if ($r['dominute'] != '' && $r['dominute'] != ',' && !in_array($min, explode(',', $r['dominute']))) {//分钟
            return false;
        }

        if ($r['lastdo']) {
            if (!$this->TogTaskTime($r, $dr)) {
                return false;
            }
        }

        return $time;
    }

    //验证时间
    protected function TogTaskTime($r, $dr) {
        $re['chdate'] = $dr[4] . '-' . $dr[5] . '-';
        $re['date'] = 'Y-m-';
        if ($r['doday']) {
            $re['chdate'].='-' . $dr[0];
            $re['date'].='-j';
        }
        if ($r['doweek']) {
            $re['chdate'].='-' . $dr[1];
            $re['date'].='-w';
        }
        if ($r['dohour']) {
            $re['chdate'].='-' . $dr[2];
            $re['date'].='-G';
        }
        if ($r['dominute']) {
            $re['chdate'].='-' . $dr[3];
            $re['date'].='-i';
        }
        if (date($re['date'], $r['lastdo']) == $re['chdate']) {
            return false;
        }
        return true;
    }

}

?>
